from django.shortcuts import get_object_or_404,render
from django.core.paginator import Paginator
from .models import Blog,BlogType
from django.db.models import Count
from django.conf import settings
from read_statistics.utils import read_statistics_once_read
# Create your views here.

# each_page_blogs_number = 5

def get_blog_list_common_data(request,blogs_all_list):

    paginator = Paginator(blogs_all_list, settings.EACH_PAGE_BLOGS_NUMBER)  # 每each_page_blogs_number页分一页
    page_num = request.GET.get('page', 1)  # 获取页码参数（GET请求）
    page_of_blogs = paginator.get_page(page_num)
    # page_of_blogs.paginator.num_pages 获取总共页码
    currentr_page_num = page_of_blogs.number  ##获取当前页码
    # 获取当前页码前后两页的范围
    page_range = list(range(max(currentr_page_num - 2, 1), currentr_page_num)) + \
                 list(range(currentr_page_num,
                            min(currentr_page_num + 2, paginator.num_pages) + 1))  ##paginator.num_pages获取最后一页的页码
    ##首页尾页与前方页码的省略号
    if page_range[0] - 1 >= 2:
        page_range.insert(0, '...')
    if paginator.num_pages - page_range[-1] >= 2:  ##注：如果最后一页减去当前最后一页大于等于2
        page_range.insert(paginator.num_pages, "...")
    ##首页与尾页号码
    if page_range[0] != 1:
        page_range.insert(0, 1)
    if page_range[-1] != paginator.num_pages:
        page_range.insert(paginator.num_pages, paginator.num_pages)


    ##获取分类博客数量
    # BlogType.objects.annotate(blog_count = Count('blog')) #等于下面的循环效果


    # blog_types = BlogType.objects.all()
    # blog_types_list = []
    # for blog_type in blog_types:
    #     blog_type.blog_count = Blog.objects.filter(blog_type = blog_type).count() #filter(name='值')
    #     blog_types_list.append(blog_type)

    #获取日期归档博客数量
    blog_dates = Blog.objects.dates('created_time', 'month', order="DESC")
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(created_time__year=blog_date.year,
                                             created_time__month=blog_date.month).count()
        blog_dates_dict[blog_date] = blog_count



    context = {}  ##定义字典

    context['blogs'] = page_of_blogs.object_list
    ##分页器
    context['page_range'] = page_range
    context["page_of_blogs"] = page_of_blogs

    context["blog_types"] =  BlogType.objects.annotate(blog_count = Count('blog'))
    context['blog_dates'] = blog_dates_dict

    return context

def blog_list(request):
    blogs_all_list = Blog.objects.all()
    context = get_blog_list_common_data(request,blogs_all_list)
    return render(request,"blog/blog_list.html",context) ##在页面显示出

def blogs_with_type(request,blog_type_pk):
    blog_type = get_object_or_404(BlogType, pk=blog_type_pk) #获取类型
    blogs_all_list = Blog.objects.filter(blog_type=blog_type)#获取所有的内容并筛选
    context = get_blog_list_common_data(request,blogs_all_list)
    context['blog_type'] = blog_type
    return render(request,"blog/blogs_with_type.html",context)

def blogs_with_date(request,year,month):

    blogs_all_list = Blog.objects.filter(created_time__year=year,created_time__month=month)#获取所有的内容并筛选
    context = get_blog_list_common_data(request,blogs_all_list)
    context['blog_with_date'] = '%s年%s月' %(year,month)
    # context['blog_dates'] = Blog.objects.dates('created_time', 'month', order="DESC")
    return render(request,"blog/blogs_with_date.html",context)

def blog_detall(request,blog_pk):
    ## pk 主键 = id
    ## blog_detall 博客的详细文章
    blog = get_object_or_404(Blog, pk=blog_pk)  # 获取具体博客
    read_cookie_key = read_statistics_once_read(request,blog)
    # blog_content_type = ContentType.objects.get_for_model(blog)
    # comments = Comment.objects.filter(content_type=blog_content_type,object_id=blog_pk,parent=None)##评论
    context={}
    context['blog']  = blog
    # Blog.objects.get(pk = blog_pk) #获取具体博客
    # context['comments'] = comments.order_by('-comment_time')

    # context['comment_form'] = CommentForm(initial={'content_type':blog_content_type.model,'object_id':blog_pk,'reply_comment_id':0})
    context['previous_blog'] = Blog.objects.filter(created_time__gt=blog.created_time).last() #gt = 大于
    context['next_blog'] = Blog.objects.filter(created_time__lt=blog.created_time).first() #lt = 小于
    response =render(request,"blog/blog_detall.html",context) #响应
    """
    .set_cookie(键,值,有效期)
    """
    """
    ##阅读次数cookie //max_age=60 60秒有效 若去掉max_age则关闭浏览器再次打开会+1
    """
    response.set_cookie(read_cookie_key, 'true' ,max_age=60)
    return response